/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ui;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Esteban
 */
public class PanelAsignarClasePaso1 extends javax.swing.JPanel {

    /**
     * Creates new form PanelAsignarClasePaso1
     */
    public PanelAsignarClasePaso1(JPanel panelCards, CardLayout cards) {
        this.cards=cards;
        this.panelCards=panelCards;
        initComponents();
        initComponents2();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        clase = new javax.swing.JLabel();
        scrollCurso = new javax.swing.JScrollPane();
        tablaCurso = new javax.swing.JTable();
        campoBusquedaCurso = new javax.swing.JTextField();
        btnSiguiente = new javax.swing.JButton();
        curso = new javax.swing.JLabel();
        horario = new javax.swing.JLabel();

        clase.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        clase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/asignar.png"))); // NOI18N
        clase.setText("Asignar Estudiante a Clase Compartida");

        scrollCurso.setBackground(new java.awt.Color(255, 255, 255));
        scrollCurso.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true), "Paso 1. Seleccione el curso:", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Calibri", 1, 18), new java.awt.Color(0, 153, 254))); // NOI18N

        tablaCurso.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        tablaCurso.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Curso"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaCurso.setGridColor(new java.awt.Color(0, 102, 204));
        tablaCurso.getTableHeader().setReorderingAllowed(false);
        scrollCurso.setViewportView(tablaCurso);

        campoBusquedaCurso.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
        campoBusquedaCurso.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                campoBusquedaCursoKeyReleased(evt);
            }
        });

        btnSiguiente.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        btnSiguiente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/siguiente.png"))); // NOI18N
        btnSiguiente.setText("Siguiente");
        btnSiguiente.setToolTipText("Siguiente paso");
        btnSiguiente.setEnabled(false);
        btnSiguiente.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        btnSiguiente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnSiguienteMousePressed(evt);
            }
        });

        curso.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        curso.setText("Buscar curso:");

        horario.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        horario.setText("Horario seleccionado:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(105, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(scrollCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 628, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(93, 93, 93))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(curso)
                        .addGap(43, 43, 43)
                        .addComponent(campoBusquedaCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(187, 187, 187))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSiguiente)
                        .addGap(348, 348, 348))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(horario)
                            .addComponent(clase))
                        .addGap(222, 222, 222))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addComponent(clase)
                .addGap(18, 18, 18)
                .addComponent(horario)
                .addGap(34, 34, 34)
                .addComponent(scrollCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoBusquedaCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(curso))
                .addGap(37, 37, 37)
                .addComponent(btnSiguiente)
                .addContainerGap(89, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void campoBusquedaCursoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoBusquedaCursoKeyReleased
        // TODO add your handling code here:
        busquedaCurso();
    }//GEN-LAST:event_campoBusquedaCursoKeyReleased

    private void btnSiguienteMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSiguienteMousePressed
        // TODO add your handling code here:
        siguiente();
    }//GEN-LAST:event_btnSiguienteMousePressed

    private void initComponents2(){
        tablaCurso.getTableHeader().setFont( new Font( "Calibri" , Font.PLAIN, 16 ));
        scrollCurso.getViewport().setBackground(Color.WHITE);
        
        ListSelectionModel listSelectionModel3 = tablaCurso.getSelectionModel();
        listSelectionModel3.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) { 
                ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                if(!lsm.isSelectionEmpty()){
                    habilitarNextPanel();
                }
                else{
                    deshabilitarNextPanel();
                }
            }
        });       
        cargarCursos();
    }
    
    private void busquedaCurso(){
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tablaCurso.getModel());
        tablaCurso.setRowSorter(sorter);
        if(campoBusquedaCurso.getText().isEmpty()){
            sorter.setRowFilter(null);
        }    
        else{
            try{
                sorter.setRowFilter(RowFilter.regexFilter(campoBusquedaCurso.getText()));
            }catch (PatternSyntaxException pse) {
                System.err.println("Bad regex pattern");
            }
        }
    }
    
    public void cargarCursos(){
        Connection conexion=null;
        Statement sentencia=null;
        ResultSet resultado=null;
        Object[][] cursos=null;
        
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            conexion = DriverManager.getConnection(cadenaConexion);
            sentencia = conexion.createStatement();
        
            String consultaSQL = "select codigo,nombre from curso where activo='true'";
            resultado = sentencia.executeQuery(consultaSQL);
            int cursosSize=0;
            while(resultado.next()){
                cursosSize++;
            }
            
            if(cursosSize!=0){
                cursos=new Object[cursosSize][2];
                cursosSize=0;
                Statement sentencia2 = conexion.createStatement();
                ResultSet resultado2 = sentencia2.executeQuery(consultaSQL);
                while (resultado2.next()) {
                    cursos[cursosSize][0]=resultado2.getInt("codigo");
                    cursos[cursosSize][1]=resultado2.getString("nombre");   
                    cursosSize++;
                }
            }
                     
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "\n Imposible cargar los cursos activos\n Error en la base de datos", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            conexion = null;
        }
        finally {
            if (resultado != null) {
                try {
                    resultado.close();
                } catch (Exception e) {
                e.printStackTrace();
                }
            }
            if (sentencia != null) {
                try {
                    sentencia.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        tablaCurso.setModel(new javax.swing.table.DefaultTableModel(
            cursos,
                
            new String [] {
                "Código", "Curso"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });  
        
        tablaCurso.getColumnModel().getColumn(0).setMaxWidth(65);
        tablaCurso.getColumnModel().getColumn(0).setMinWidth(65);
        
    }
    
    private void habilitarNextPanel(){
        btnSiguiente.setSelected(true);
        btnSiguiente.setEnabled(true);
    }
    
    private void deshabilitarNextPanel(){
        btnSiguiente.setSelected(false);
        btnSiguiente.setEnabled(false);
    }
    
    private void siguiente(){
        setOpcionesPaso2();
        cards.next(panelCards);
    }
    
    public void setListaPaneles(ArrayList<JPanel> lista){
        paneles=lista;
    }
    
    public int getCursoSeleccionado(){
        return (int)tablaCurso.getValueAt(tablaCurso.getSelectedRow(), 0);
    }
    
    private void setOpcionesPaso2(){
        ((PanelAsignarClasePaso2)paneles.get(1)).setOpciones((String)tablaCurso.getValueAt(tablaCurso.getSelectedRow(), 1),getCursoSeleccionado(),"Horario: "+((PanelAsignarClasePaso3)paneles.get(2)).getDia2()+" "+((PanelAsignarClasePaso3)paneles.get(2)).getHoraInicio2()+" - "+((PanelAsignarClasePaso3)paneles.get(2)).getHoraFin2());
    }  
    
    public void setHorario(String dia, String hora_inicio, String hora_fin){
        horario.setText("Horario: "+dia+" "+hora_inicio+" - "+hora_fin);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSiguiente;
    private javax.swing.JTextField campoBusquedaCurso;
    private javax.swing.JLabel clase;
    private javax.swing.JLabel curso;
    private javax.swing.JLabel horario;
    private javax.swing.JScrollPane scrollCurso;
    private javax.swing.JTable tablaCurso;
    // End of variables declaration//GEN-END:variables
    private static final String cadenaConexion = "jdbc:postgresql://localhost/SMAAMDB?" + "user=postgres&password=root";
    private CardLayout cards;
    private JPanel panelCards;
    private ArrayList<JPanel> paneles;
}
